package com.share.ocr;

import com.baidu.aip.ocr.AipOcr;
import org.json.JSONArray;
import org.json.JSONObject;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.net.URLDecoder;
import java.util.Base64;
import java.util.HashMap;

/**
 * author:caifan
 * date:2019/10/7
 */
public class BaiduOCR {
    public static final String APP_ID = "17443928";
    public static final String API_KEY = "wypdLI6RXN7Se41FrmFj3yo3";
    public static final String SECRET_KEY = "Xr2PQ2iogFkQDXY8wmcfU1cgGpu1IKzC";

    public static String textOCR(byte[] bytes) throws Exception {
        // 初始化一个AipOcr
        AipOcr client = new AipOcr(APP_ID, API_KEY, SECRET_KEY);

        // 可选：设置网络连接参数
        client.setConnectionTimeoutInMillis(2000);
        client.setSocketTimeoutInMillis(60000);

        // 可选：设置log4j日志输出格式，若不设置，则使用默认配置
        // 也可以直接通过jvm启动参数设置此环境变量
        System.setProperty("aip.log4j.conf", "./baidu/log4j.properties");

        // 调用接口
        String path = "D:/data/test.png";
//        client.basicGeneral()
        ImageIcon imageIcon = new ImageIcon("E:/发票验证/201912发票验证.png");
        BufferedImage image = new BufferedImage(imageIcon.getImage().getWidth(null),imageIcon.getImage().getHeight(null), BufferedImage.TYPE_INT_RGB);

        ByteArrayOutputStream imageStream = new ByteArrayOutputStream();
        ImageIO.write(image, "png", imageStream);
        Base64.Encoder encoder = Base64.getEncoder();

        JSONObject res = client.basicGeneral(encoder.encode(imageStream.toByteArray()), new HashMap<String, String>());
        JSONArray wordsResults = res.getJSONArray("words_result");
        StringBuffer buffer = new StringBuffer();
        for (Object obj : wordsResults) {
            JSONObject json  = (JSONObject)obj;
            String word = json.getString("words");
            word = URLDecoder.decode(word, "UTF-8");
            buffer.append(word);
        }
        return buffer.toString();
    }

    public static void main(String[] args) throws Exception {
        String aa = textOCR(null);
        System.out.println(aa);
    }
}
